package com.szh.htmltopdf.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.szh.htmltopdf.constants.MyAppConstant;
import com.szh.htmltopdf.mapper.SysRegionMapper;
import com.szh.htmltopdf.model.SysRegion;
import com.szh.htmltopdf.service.SysRegionService;
import com.szh.htmltopdf.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
@Slf4j
public class SysRegionServiceImpl extends ServiceImpl<SysRegionMapper, SysRegion> implements SysRegionService {

    @Resource
    RedisUtil redisUtil;


    @Override
    public List<SysRegion> areaTree() {
        List<SysRegion> regionList = this.list();
        List<SysRegion> collect = regionList.stream().filter(area -> Objects.equals(area.getRegionParentId(), "-1"))
                .peek(menu -> menu.setChildren(getChildren(menu, regionList))).collect(Collectors.toList());
        String s = JSONUtil.toJsonStr(collect);
        redisUtil.set(MyAppConstant.AREA_TREE_KEY, s);
        return collect;
    }

    private List<SysRegion> getChildren(SysRegion menu, List<SysRegion> all) {
        return all.stream().filter(cate -> cate.getRegionParentId().equals(menu.getRegionId())).peek(cate -> cate.setChildren(getChildren(cate, all))).collect(Collectors.toList());
    }
}
